<?php
namespace jy_globonus;
defined('BY_JYA') or exit('error');
/*
	分销插件工具类
*/
class model extends \plugin{
	public function get_redfee($order=array()){
		$order_price=$order['price'];
		if($order_price<=0){
			return 0;
		}
		$allgoods=pdo_getall('jy_weishop_order_goods',array('orderid'=>$order['id']),array('optionid','goodsid','total','price','total_price'));
		$total_lastcostprice=0;
		$this->needorder=false;
		$money=0;
		foreach($allgoods as $gv){
			$total_price=$gv['total_price']?:$gv['total']*$gv['price'];
			if($gv['optionid']){
				$shopgoods=pdo_get('jy_weishop_goods_option',array('id'=>$gv['optionid'],'uniacid'=>$_SESSION['uniacid']),array('costprice'));
				$shopgoods['pcate']=pdo_getcolumn('jy_weishop_goods',array('id'=>$gv['goodsid'],'uniacid'=>$_SESSION['uniacid']),'pcate');
			}else{
				$shopgoods=pdo_get('jy_weishop_goods',array('id'=>$gv['goodsid'],'uniacid'=>$_SESSION['uniacid']),array('pcate','costprice'));
			}
			$costprice=$shopgoods['costprice'];
			$total_costprice=$gv['total']*$costprice;
			$total_lastcostprice +=$total_costprice;
			$goods_set=$this->get('goods',array('merchid'=>$_SESSION['onemerchid'],'goods_id'=>$gv['goodsid']));
			if($goods_set['ignore'] || !$goods_set['id']){
				if($goods_set['ignore']){
					$order_price=$order_price-$total_price;
				}
				//只要有一个商品，没有独立设置分销，就订单计算佣金
				$this->needorder=true;
				continue;
			}
			if($order_price<$total_price){
				$total_price=$order_price;
			}
			//利润计算
			if($this->setting['fenxiaototal_types']==2){
				$total_price -=$total_costprice;
				$total_lastcostprice -=$total_costprice;
			}
			$order_price=$order_price-$total_price;
			if(substr($goods_set['red_rate'],-1)=='%'){
				$goods_red_money=intval($total_price*substr($goods_set['red_rate'],0,-1))/100;
			}else{
				$goods_red_money=$goods_set['red_rate']*$gv['total'];
			}
			$money+=$goods_red_money;
		}
		if($this->needorder){
			$rate=$this->setting['rate']?:10;
			if($order_price>0 && $rate){
				if(substr($rate,-1)=='%'){
					//利润计算
					if($this->setting['fenxiaototal_types']==2){
						$order_price -=$total_lastcostprice;
					}
					$order_red_money=intval($order_price*substr($rate,0,-1))/100;
				}else{
					$order_red_money=$rate;
				}
				$money+=$order_red_money;
			}
		}
		$money=intval($money*100)/100;
		return $money;
	}
	public function check_bill($bill_id,$status,$remark=''){
		if(!$bill_id || !$status){
			exi('订单不存在！','error');
		}
		$bill=$this->get('bill',array('id'=>$bill_id));
		if(!$bill){
			exi('订单不存在！','error');
		}
		$update=array(
			'status'=>$status==2?3:$status,
			'confirmtime'=>TIMESTAMP,
		);
		if($update['status']==2){
			$update['remark']=$remark;
		}elseif($update['status']==1){
			if($this->setting['iskao'] && $this->setting['kao_rate']){
				if($bill['week']==1){
					$year=$bill['year'];
					$month=$bill['month']-1;
					$week=4;
				}elseif($bill['week']>1){
					$year=$bill['year'];
					$month=$bill['month'];
					$week=$bill['week']-1;
				}else{
					$year=$bill['year'];
					$month=$bill['month']-1;
					$week=0;
				}
				$lastbill=pdo_get('jy_globonus_bill',array('uniacid'=>$_SESSION['uniacid'],'year'=>$year,'month'=>$month,'week'=>$week));
				if(!$lastbill['id']){
					$date=$year.'-'.$month;
					if($week){
						$date .='第'.$week.'周';
					}
					exi($date.'的分红还未结算，不能跨周期！','error');
				}
				if($this->setting['kao_feemax'] && $lastbill['bonusmoney']<$this->setting['kao_feemax']){
					if($lastbill['bonusmoney']<$bill['bonusmoney']+$bill['bonusmoney']*$this->setting['kao_rate']/100){
						exi('本期分红增长比例小于'.$this->setting['kao_rate'].'%，不能分红！','error');
					}
				}
			}
			$firstday=$bill['starttime'];
			$lastday=$bill['endtime'];
			$params=array('merchid'=>$_SESSION['onemerchid'],'uniacid'=>$_SESSION['uniacid'],'ispartner'=>'1','partnerstatus'=>1,'partnertime <'=>$lastday);
			$partnercount=pdo_count('jy_weishop_member',$params,'mid');
			$levels=pdo_getall('jy_globonus_level',array('merchid'=>$_SESSION['onemerchid'],'uniacid'=>$_SESSION['uniacid']),array('id','bonus'),'id');
			$bonusmoney_send=$bill['bonusmoney_send'];
			if($bonusmoney_send){
				//等级股东
				foreach($levels as &$lv){
					if(!$lv['bonus']){
						continue;
					}
					$feerate=$lv['bonus'];
					$fee=intval($feerate*$bill['bonusmoney_send'])/100;
					$this->upfee($lv,$fee,$lastday,$bill['id']);
				}
			}
		}
		$this->update('bill',$update,array('id'=>$bill_id));
		return true;
	}
	public function check_jiebill($bill_id=0){
		if(!$bill_id){
			exi('结算ID不能为空！','error');
		}
		$bill=$this->get('bill',array('id'=>$bill_id));
		if(!$bill){
			exi('结算单不存在！','error');
		}
		if($this->setting['withdrawtype']==2){
			exi('暂不支持付款到零钱！结算失败！请移步：基本设置--结算--结算方式修改！','error');
		}
		$billps=pdo_getall('jy_globonus_billp',array('merchid'=>$_SESSION['onemerchid'],'billid'=>$bill_id,'uniacid'=>$_SESSION['uniacid'],'status'=>0));
		foreach($billps as $mv){
			if($mv['paytype']!=2){
				if($_SESSION['onemerchid']){
					model('jy_merch/member')->member_credit($_SESSION['onemerchid'],$mv['uid'],'credit2',$mv['realmoney'],true,'jy_globonus','股东分红');
				}else{
					model('core/member')->member_credit($mv['uid'],'credit2',$mv['realmoney'],true,'jy_globonus','股东分红');
				}
				$this->update('billp',array('status'=>1,'paytime'=>time()),array('uniacid'=>$_SESSION['uniacid'],'id'=>$mv['id']));
			}else{
				if($mv['paytype']==2){
					exi('暂不支持付款到零钱！结算失败！请移步：基本设置--结算--结算方式修改！','error');
				}
			}
		}
		$update=array(
			'status'=>2,
			'paytime'=>TIMESTAMP,
		);
		$this->update('bill',$update,array('id'=>$bill_id));
		return true;
	}
	public function upfee($lv,$fee=0,$lastday=0,$billid=0){
		if($this->setting['withdrawtype']==2){
			exi('暂不支持付款到零钱！结算失败！请移步：基本设置--结算--结算方式修改！','error');
		}
		$params=array('partnerlevel'=>$lv['id'],'merchid'=>$_SESSION['onemerchid'],'uniacid'=>$_SESSION['uniacid'],'ispartner'=>'1','partnerstatus'=>1,'partnertime <'=>$lastday);
		$members=pdo_getall('jy_weishop_member',$params);
		$num=count($members);
		if(!$num){
			return false;	
		}
		$onemoney=$fee/$num;
		$chargemoney=$this->setting['withdrawcharge']?intval($this->setting['withdrawcharge']*$onemoney)/100:0;
		$realmoney=$onemoney-$chargemoney;
		$data=array(
			'uniacid'=>$_SESSION['uniacid'],
			'billid'=>$billid,
			'money'=>$fee,
			'realmoney'=>$realmoney,
			'paymoney'=>$realmoney,
			'charge'=>$this->setting['withdrawcharge'],
			'chargemoney'=>$chargemoney,
			'paytype'=>$this->setting['withdrawtype'],
		);
		foreach($members as $mv){
			if($mv['maxred']>0){
				$isred=pdo_getsum('jy_globonus_billp',array('uniacid'=>$_SESSION['uniacid'],'uid'=>$mv['mid'],'merchid'=>$_SESSION['onemerchid']),'realmoney');
				if($isred>=$mv['maxred']){
					continue;
				}else{
					$lastred=$mv['maxred']-$isred;
					if($lastred<$data['realmoney']){
						$data['realmoney']=$data['realmoney']-$lastred;
						$data['paymoney']=$data['realmoney'];
					}
				}
			}
			$data['uid']=$mv['mid'];
			$data['createtime']=time();
			$data['merchid']=$_SESSION['onemerchid'];
			pdo_insert('jy_globonus_billp',$data);
		}
		return true;
	}
	public function create_condition($conditions){
		if(!$conditions){
			return '';
		}
		if(!is_array($conditions)){
			$conditions=json_decode($conditions,true);
		}
		$level_up_types=$this->level_up_types;
		$current_level_up_types=$this->current_level_up_types();
		$str='';
		foreach($current_level_up_types as $key){
			$str.=$level_up_types[$key].'达'.$conditions[$key].';';
		}
		return $str;
	}
	public function current_level_up_types(){
		return str_array($this->setting['level_up_types']);
	}
		/*
		升级分销商等级
		先检测会员身份是否为正常分销商
		然后获取分销商当前等级的下一等级升级条件
		然后逐个条件对比，看是否满足升级条件
		如果全部满足，则升级到相应等级
		
		何时触发升级分销商等级检测呢？
		
	*/
	public function update_agent_level($mid){
		//
		$member=pdo_get('jy_weishop_member',array('merchid'=>$_SESSION['onemerchid'],'mid'=>$mid));
		if(!$member['partnerstatus'] || $member['isblack']){
			return;
		}
		$level=$this->get('level',array('id'=>$member['level']));
		$parameter=array(
			'params'=>array('merchid'=>$_SESSION['onemerchid'],'uniacid'=>$_SESSION['uniacid'],'level >'=>$level['level']),
			'order_by'=>'level asc',
			'limit'=>'1',
		);
		$levels=$this->get_list('level',$parameter);
		$next_level=$levels[0];
		if(!$next_level){
			return;
		}
		$conditions=json_decode($next_level['conditions'],true);
		$level_up_types=$this->model()->current_level_up_types();//获取当前设置的分销商等级升级条件
		if(!$level_up_types){
			return;
		}
		$up=true;
		foreach($level_up_types as $type){
			if($member[$type]<$conditions[$type]){
				$up=false;
				break;
			}
		}
		if($up){
			$update=array(
				'level'=>$next_level['id'],
			);
			pdo_update('jy_weishop_member',$update,array('mid'=>$mid));
		}
		return true;
	}
	public function get_rate(){
		return str_array($this->setting['level_up_types']);
	}
}